package com.example.administrator.trains;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserFragment extends Fragment {
    Button btn_search;
    ImageButton ibtn_add;
    ImageButton ibtn_flash;
    private byte one_data;
    private int k = 0;
    List<Map<String,String>> list2 = new ArrayList<Map<String, String>>();
    List<Map<String,String>> list3 = new ArrayList<Map<String, String>>();

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                ListView lv = (ListView) getActivity().findViewById(R.id.lv);
                ListAdapter la = new SimpleAdapter(getActivity(), list2,
                        R.layout.activity_show_list_item3,
                        new String[]{"id", "code", "identity", "phone", "name"},
                        new int[]{R.id.ID, R.id.code,
                                R.id.identify, R.id.phone,
                                R.id.name});
                lv.setAdapter(la);


                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent i = new Intent(getActivity(),admin_change_user.class);

                        i.putExtra("id",list2.get(position).get("id").toString());
                        i.putExtra("code",list2.get(position).get("code").toString());
                        i.putExtra("identity",list2.get(position).get("identity").toString());
                        i.putExtra("phone",list2.get(position).get("phone").toString());
                        i.putExtra("name",list2.get(position).get("name").toString());

                        startActivity(i);
                    }
                });}
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        btn_search = (Button)view.findViewById(R.id.search);
        ibtn_add = (ImageButton)view.findViewById(R.id.imageButton2);
        ibtn_flash = (ImageButton)view.findViewById(R.id.imageButton4);
        btn_search.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape2));
                        break;
                    case MotionEvent.ACTION_UP:
                        v.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape));
                        btn_search.performClick();
                        break;
                }
                return true;
            }
        });
        /*接收用户数据*/
        recv_user_msg();
        /*按刷新重新接收用户数据*/
        ibtn_flash.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                recv_user_msg();
            }
        });
        /*按加号添加车票*/
        ibtn_add.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), admin_add_user.class);
                startActivity(i);
            }
        });
        /*按搜索在map中搜索出符合要求的用户*/
        btn_search.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                EditText user_text = (EditText)getActivity().findViewById(R.id.edt_user_id);
                String user_id = user_text.getText().toString();
                if (!user_id.matches("[0-9a-zA-Z]{5,10}")) {
                    Toast.makeText(getActivity(), "ID格式不对，请不要输入字母以外的字符,要求为5到10个字符组成", Toast.LENGTH_LONG).show();
                    return;
                }
                list3.clear();
                for (int i = 0; i < list2.size(); i++) {
                    if (list2.get(i).get("id").equals(user_id)){
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("id", list2.get(i).get("id"));
                        map.put("code", list2.get(i).get("code"));
                        map.put("identity", list2.get(i).get("identity"));
                        map.put("phone", list2.get(i).get("phone"));
                        map.put("name", list2.get(i).get("name"));
                        list3.add(map);
                    }
                }
                ListView lv = (ListView) getActivity().findViewById(R.id.lv);
                ListAdapter la = new SimpleAdapter(getActivity(), list3,
                        R.layout.activity_show_list_item3,
                        new String[]{"id", "code", "identity", "phone", "name"},
                        new int[]{R.id.ID, R.id.code,
                                R.id.identify, R.id.phone,
                                R.id.name});
                lv.setAdapter(la);
            }
        });
        return view;
    }

    private void recv_user_msg(){
        try {
            Socket.connector.send(Socket.connector.package_data(Socket.connector.LOGIN_CMD_TYPE,
                    Socket.connector.ALL_USER, "00", "00"));
            Socket.connector.recv_ack();
            if (CommunicationData.ack == "01") {
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        list2.clear();
                        byte[] buffer = new byte[20000];
                        int j = 1;
                        byte[] one_user = new byte[30];
                        byte[] id = new byte[30];
                        byte[] code = new byte[10];
                        byte[] identity = new byte[5];
                        byte[] phone_num = new byte[5];
                        byte[] name = new byte[5];

                        try {
                            //接收对应车次的当天的车票
                            Socket.connector.rec_data(buffer);
                            Socket.connector.send(Socket.connector.hexStringToByteArray(Socket.connector.ACK_OK));
                        } catch (IOException e) {
                        }

                        for (int i = 7; i > 0; i++) {
                            one_data = buffer[i];
                            if (one_data == '|') {
                                switch (j) {
                                    case 1:
                                        id = one_user.clone();
                                        break;
                                    case 2:
                                        code = one_user.clone();
                                        break;
                                    case 3:
                                        name = one_user.clone();
                                        break;
                                    case 4:
                                        identity = one_user.clone();
                                        break;
                                    case 5:
                                        phone_num = one_user.clone();
                                        break;
                                }
                                while (k >= 0) {
                                    one_user[k] = 0;
                                    k--;
                                }
                                k = 0;
                                j++;
                                continue;
                            }
                            /*读完一条车票信息，加入map中*/
                            if (one_data == ',') {
                                String str_id = new String(id).trim();
                                String str_code = new String(code).trim();
                                String str_identity = new String(identity).trim();
                                String str_phone_num = new String(phone_num).trim();
                                String str_name = new String(name).trim();

                                /*把数据保存在list2中*/
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("id", str_id);
                                map.put("code", str_code);
                                map.put("identity", str_identity);
                                map.put("phone", str_phone_num);
                                map.put("name", str_name);
                                list2.add(map);

                                k = 0;
                                j = 1;
                                continue;
                            }
                            if (one_data == '.') {
                                break;
                            }
                            one_user[k] = one_data;
                            k++;
                        }

                        Message m = new Message();
                        m.what=1;
                        myHandler.sendMessage(m);
                    }
                }.start();
            }
        }catch (IOException e){
        }
    }
}